﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Net;
using System.Text;
using SS.Common.Logging;
using SS.Common.Utilities;

namespace SS.Common.Map.CountryDetect
{
    [Export(typeof(CountryDetector))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class CountryDetector
    {
        #region Fields

        private const string UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2";
        private const string Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        private readonly CookieContainer _cookies = new CookieContainer();
        private static readonly ILogger Logger = LoggerManager.GetLogger(typeof(CountryDetector).Name);

        #endregion

        #region Public methods
        
        /// <summary>
        /// Request to service to detect country
        /// </summary>
        /// <param name="svcUrl">URL of service that provides detecting country</param>
        /// <returns></returns>
        public Response DetectCountry(string svcUrl)
        {
            #region Xml response

            //<Response>
            //    <Ip>14.161.70.37</Ip>
            //    <CountryCode>VN</CountryCode>
            //    <CountryName>Vietnam</CountryName>
            //    <RegionCode>20</RegionCode>
            //    <RegionName>Ho Chi Minh</RegionName>
            //    <City>Ho Chi Minh City</City>
            //    <ZipCode/>
            //    <Latitude>10.8142</Latitude>
            //    <Longitude>106.6438</Longitude>
            //    <MetroCode/>
            //    <AreaCode/>
            //</Response>

            #endregion

            Logger.Info("DetectCountry --> Start");
            Response response = null;
            try
            {
                var xmlResponse = this.GetContentUsingHttp(svcUrl);
                if (!string.IsNullOrEmpty(xmlResponse))
                {
                    Logger.InfoFormat("Result: {0}", xmlResponse);
                    response = XMLHelper<Response>.Load(xmlResponse);
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Error: {0}", ex.ToString());
            }
            Logger.Info("DetectCountry <-- End");
            return response;
        }
        
        #endregion

        #region Help methods

        /// <summary>
        /// Request to service to get current geo location
        /// </summary>
        /// <param name="svcUrl">URL of service that provides detecting country</param>
        /// <returns></returns>
        private string GetContentUsingHttp(string svcUrl)
        {
            string ret;
            var request = (HttpWebRequest)WebRequest.Create(svcUrl);
            request.Accept = Accept;
            request.KeepAlive = true;
            request.Timeout = 0x7530;
            request.ReadWriteTimeout = 0x7530;
            request.Method = "GET";
            request.UserAgent = UserAgent;
            request.CookieContainer = this._cookies;
            request.Referer = svcUrl;

            using (var response = request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader read = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        ret = read.ReadToEnd();
                    }
                }
                response.Close();
            }

            return ret;
        }

        #endregion
    }
}
